package com.cx.mall.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

@Configuration
public class MybatisPLusConfig {

    //配置分页插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); //分页插件
//        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); //乐观锁插件
//        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); //防止全表更新与删除插件
        return interceptor;
    }

    @Bean
    public MetaObjectHandler metaObjectHandler() {
       return new MetaObjectHandler() {
           @Override
           public void insertFill(MetaObject metaObject) {
               this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
               this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
               this.strictInsertFill(metaObject, "status", Integer.class, 0);
               this.strictInsertFill(metaObject, "deleted", Integer.class, 0); //逻辑删除字段 0-未删除 1-已删除
               this.strictInsertFill(metaObject, "version", Integer.class, 1);
           }

           @Override
           public void updateFill(MetaObject metaObject) {
               this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
           }
       };
    }
}
